$(() => {
   const Editor = toastui.Editor;
   const { codeSyntaxHighlight } = Editor.plugin;
   const viewer = Editor.factory({
      el: document.querySelector('#viewer'),
      viewer: true,
      initialValue: '',
      plugins: [codeSyntaxHighlight],
   });;
   const id = document.documentElement.getAttribute('data-id')
   $.get('/read', { id }, res => {
      const { article } = res
      $('#articleContentId').text(article.title)
      $('#spanCount').text(res.agree)
      console.log(res);
      $('title').text(article.title)
      if (res.isAgree) {
         $('#isAgree').addClass('isAgree')
      }
      $('#isAgree').on('click', function () {
         const t = $(this)
         if (t.hasClass('isAgree')) {
            $.get('/api/agree/cancel', { id }, res => {
               const { code } = res
               if (code == 200) {
                  t.removeClass('isAgree')
                  const agree_count = t.find('.agree_count')
                  agree_count.text(+agree_count.text() - 1)
               } else if (code == 401 || code == 402) {
                  location.href = '/view/login'
               } else {
                  console.log(code);
               }
            })
         } else {
            $.get('/api/agree', { id }, res => {
               const { code } = res
               if (code == 200) {
                  t.addClass('isAgree')
                  const agree_count = t.find('.agree_count')
                  agree_count.text(+agree_count.text() + 1)
               } else if (code == 401 || code == 402) {
                  location.href = '/view/login'
               } else {
                  console.log(code);
               }
            })
         }
      })
      $('#pushdate').text((new Date(article.pushdateAt)).toLocaleString())
      $('._nickname_text').text(res.nickname)
      $('._profile_img').prop('src', '/profile/' + res.profile)
      $('#read').text(article.read)
      $('#original').text(res.original)
      $('.tags-box').html(`
      <span class="label">分类专栏：</span>
      ${article.classif.split(' ').map(a => `<a href="javascript:;" class="tag-link">${a}</a>`).join('')}
      <span class="label">文章标签：</span>
      ${article.tag.split(' ').map(a => `<a href="javascript:;" class="tag-link">${a}</a>`).join('')}
      `)
      viewer.setMarkdown(article.main)
   })
})